﻿using System;
using System.Data.Services.Client;
using System.Linq;

namespace Songhay.Silverlight.BiggestBox.IndexPart.ServiceContext
{
    using NetflixServiceReference;

    /// <summary>
    /// Netflix Context
    /// </summary>
    /// <remarks>
    /// This class is informed by the Silverlight 4 Netflix Browser
    /// [http://silverlight4netflix.codeplex.com/]
    /// </remarks>
    public static partial class NetflixContext
    {
        /// <summary>
        /// Initializes the <see cref="NetflixContext"/> class.
        /// </summary>
        static NetflixContext()
        {
            NetflixContext.serviceContext = new NetflixCatalog(new Uri("http://odata.netflix.com/Catalog/"));
        }

        /// <summary>
        /// Gets the Netflix genres.
        /// </summary>
        /// <value>The Netflix genres.</value>
        public static DataServiceCollection<Genre> NetflixGenres
        {
            get { return NetflixContext.netflixGenres; }
        }

        /// <summary>
        /// Loads the genres.
        /// </summary>
        /// <param name="completeAction">The complete action.</param>
        public static void LoadGenres(Action<object, LoadCompletedEventArgs> completeAction)
        {
            if(completeAction == null) throw new ArgumentNullException("completeAction", "The Load Complete Action is null");

            var query = NetflixContext.serviceContext.Genres.OrderBy(i => i.Name);

            NetflixContext.netflixGenres = new DataServiceCollection<Genre>();
            NetflixContext.netflixGenres.LoadCompleted += (s, args) =>
            {
                if(NetflixContext.netflixGenres.Continuation != null)
                {
                    NetflixContext.netflixGenres.LoadNextPartialSetAsync();
                }
                completeAction.Invoke(s, args);
            };

            NetflixContext.netflixGenres.LoadAsync(query);
        }

        /// <summary>
        /// Loads the titles by selected genre.
        /// </summary>
        /// <param name="selectedGenre">The selected genre.</param>
        /// <param name="completeAction">The complete action.</param>
        public static void LoadTitlesBySelectedGenre(Genre selectedGenre, Action<object, LoadCompletedEventArgs> completeAction)
        {
            if(completeAction == null) throw new ArgumentNullException("completeAction", "The Load Complete Action is null");
            if(selectedGenre == null) throw new ArgumentNullException("selectedGenre", "The Load Complete Action is null");

            selectedGenre.Titles.LoadCompleted += (s, args) => completeAction.Invoke(s, args);
            selectedGenre.Titles.LoadAsync();
        }

        static readonly NetflixCatalog serviceContext;

        static DataServiceCollection<Genre> netflixGenres;
    }
}
